#coding=utf-8

import logging
import functools
from google.appengine.api import users
from google.appengine.api import memcache
import datetime
import unicodedata
import tornado.web
import tornado.escape
from lib import markdown
import constants

_ICAL_PRODID = '-//Google Inc//Google Calendar 70.9054//EN'
_ICAL_VERSION = '2.0'
class CalInfo:
    summary              = ""
    lunar_birthday_str   = ""
    location             = ""
    description          = ""
    start_year           = 2009
    end_year             = 2009
    
    def create_cal_ics(self):
        cal = Calendar()
        cal.add('prodid', _ICAL_PRODID)
        cal.add('version', _ICAL_VERSION)
        lunarCal = LunarCalendar()
        [y, m, d] = self.lunar_birthday_str.split('-')
        for i in range(self.start_year, self.end_year):
            (s_y, s_m, s_d) = lunarCal.getSolarDate(int(i), int(m), int(d))
            event = Event()
            event.add('summary', self.summary)
            event.add('dtstart', datetime(s_y, s_m, s_d, tzinfo=UTC))
            event.add('dtend', datetime(s_y, s_m, s_d, tzinfo=UTC))
            event.add('dtstamp', datetime(s_y, s_m, s_d, tzinfo=UTC))
            event.add('location', self.location)
            event.add('description', self.description)
            cal.add_component(event)
        cal_str = cal.as_string()
        self.ics_content = unicode(cal_str, 'utf-8')
        self.save();
        return cal_str

class BaseController(tornado.web.RequestHandler):

    def render_response_string(self, template_name, **kwargs):
        # Let the templates access the users module to generate login URLs
        return tornado.web.RequestHandler.render_string(
            self, template_name,   
            **kwargs)
    
    def render_response(self, template_name, **kwargs): 
        self.render(template_name,
                    user=user,
                    **kwargs)
    
    def render_json(self, val):
        self.write(tornado.escape.json_encode(val))
    
    def get_error_html(self, status_code):
        if status_code == 404 or status_code == 403:
            msg = '抱歉，所访问的资源不存在。'
        else:
            msg = '抱歉，所访问的资源不存在。'
        return self.render_string('error.html', error_msg=msg)

### Decorators for request handlers ###
def login_required(method):
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if not users.get_current_user():
            if self.request.method == "GET":
                self.redirect(users.create_login_url(self.request.uri))
                return
            raise tornado.web.HTTPError(403)
        else:
            return method(self, *args, **kwargs)
    return wrapper

def admin_required(method):
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if not users.get_current_user():
            if self.request.method == "GET":
                self.redirect(users.create_login_url(self.request.uri))
                return
            raise tornado.web.HTTPError(403)
        elif not users.is_current_user_admin():
            if self.request.method == "GET":
                self.redirect("/")
                return
            raise tornado.web.HTTPError(403)
        else:
            return method(self, *args, **kwargs)
    return wrapper

############## controllers  ############
class HomeController(BaseController):
    def get(self):
        self.render_response('home.html')

class CalController(BaseController):
    def get(self):
        sefl.render_response('lunarbirthday.html')
    def post(self):
        cal_info = CalInfo()
        cal_info.summary = self.get_argument('summary', '')
        cal_info.lunar_birthday_str = self.get_argument('birthday')
        cal_info.start_year = int(self.get_argument('startYear'))
        cal_info.end_year = int(self.get_argument('endYear'))
        cal_info.location = self.get_argument('location', '')
        cal_info.description = self.get_argument('description', '')
        ics_str = cal_info.create_cal_ics();
        filename = 'birthday.ics'
        self.set_header('Content-Type', 'application/octet-stream')
        self.set_header('Content-Disposition', 'attachment; filename=%s' % filename.encode('utf8'))
        self.write(ics_str)
        
        